<?php

    /**
     * Compiler
     *
     * This is the compiler of locales: it converts a CSV file to a serialized array
     *
     * @package      Core
     * @subpackage   Locale
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    class Core_Locale_Compiler
    {

	////////////////////////////////////////////////////////////////////////////
	//                             Static Methods                             //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Retrieves the translations of a CSV file for a module.
         * It stores the result in a temporary file
         *
         * @param		Core_Selector_Locale    $selector : the selector of the locale
		 * @param		string			        $locale : the language code
		 * @throws		Core_ArgumentException
		 * @throws		Core_ArgumentNullException
         * @return      array			an array which contains the translation
         */
        public static function get(Core_Selector_Locale $selector, $locale)
        {
            if ($locale === null) {
				throw new Core_ArgumentNullException('locale is a null reference');
			}

            if (strlen(trim($locale)) == 0) {
				throw new Core_ArgumentException('locale is a zero-length string');
			}

            $translations = array();
            $file = $selector->getPath();
            $cachefile = $selector->getCachePath();

            if (Core_IO_File::exists($file)) {
                $registry = Zend_Registry::getInstance();

                $mustCompile = $registry['config']->compilation->force || !Core_IO_File::exists($cachefile);

                if (!$mustCompile) {
                    if (@filemtime($file) > @filemtime($cachefile)) {
                        $mustCompile = true;
                    }
                }

                if ($mustCompile) {
                    $parser = new Core_Parser_Csv();
                    $csv = $parser->read($file);

                    foreach ($csv as $line) {
                        if (count($line) > 1) {
                            $translations[$line[0]] = $line[1];
                        }
                    }

                    unset($csv);

                    Core_IO_File::writeAll($cachefile, var_export($translations, true));
                } else {
                    $str = Core_IO_File::readAll($cachefile);
                    $translations = eval('return '. $str .';');
                }
            }

            return $translations;
        }
    }
